package com.itboye.mengwu.wxapi;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.login.ui.BindTelephoneActivity;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.logincontroller.LoginController;
import com.itboye.mengwu.app.logincontroller.LoginedState;
import com.itboye.mengwu.app.ui.main.MainPresenter;
import com.itboye.mengwu.data.model.PersonDataBean;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler,
		Observer {

	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;

	private IWXAPI api;
	private String code;

	public static String DISMISSFRAGMENT = "com.itboye.sunsun.dismiss";
	public static String NotifyPerson = "com.itboye.sunsun.notify.person";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.entry);

		//
		api = WXAPIFactory.createWXAPI(this, "wxae95316b3a4998a6", false);

		api.handleIntent(getIntent(), this);
		SendAuth.Resp resp = new SendAuth.Resp(getIntent().getExtras());
		code = resp.code;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		api.handleIntent(intent, this);

	}

	@Override
	public void onReq(BaseReq req) {

		WXEntryActivity.this.finish();

	}

	@Override
	public void onResp(BaseResp resp) {

		this.finish();

		int result = 0;

		code = ((SendAuth.Resp) resp).code;
		// Toast.makeText(getApplicationContext(), code + "hui", 0).show();
		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			result = R.string.errcode_success;

			if (resp.transaction.equals("sessionwebpage")) {
				Toast.makeText(MainApplication.context, "分享成功", 0).show();
				// Intent intent=new Intent(DISMISSFRAGMENT);
				// sendBroadcast(intent);
				this.finish();

			}
			if (resp.transaction.equals("webpage")) {
				// Toast.makeText(MainApplication.context, "分享成功", 0).show();
				// Intent intent=new Intent(DISMISSFRAGMENT);
				// sendBroadcast(intent);
			}
			// resp.fromBundle(arg0);
			// Log.v("code", code);

			Log.e("hu    214", "" + resp.transaction);
			// 如果是微信登录
			if (resp.transaction.equals("login")) {

				wechatLogin(code);
				// WeChatNet.getInstance().getAccessToken(code);
			}
			// 如果是绑定手机
			else if (resp.transaction.equals("bind")) {
				// wechatBind(code, (String)
				// SPUtils.get(MainApplication.context, null,
				// SPContants.USER_ID, ""));
				WXEntryActivity.this.finish();
			}

			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:
			result = R.string.errcode_cancel;
			WXEntryActivity.this.finish();
			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:
			result = R.string.errcode_deny;
			WXEntryActivity.this.finish();
			break;
		default:
			result = R.string.errcode_unknown;
			WXEntryActivity.this.finish();
			break;
		}

		// Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}

	// private void wechatBind(String code, String uid) {
	//
	// MyJsonRequest<String> request = new
	// MyJsonRequest.Builder<String>().apiVer("100").typeKey("BY_Weixin_bind")
	// .param("code", code).param("uid", uid).requestListener(new
	// XRequestListener<String>() {
	//
	// @Override
	// public void onResponse(String response) {
	// // TODO Auto-generated method stub
	// DebugLog.v("result", response.toString());
	// Toast.makeText(MainApplication.context, "绑定成功", 0).show();
	// Intent intent = new Intent(NotifyPerson);
	// sendBroadcast(intent);
	//
	// }
	// }).errorListener(new XErrorListener() {
	//
	//
	// @Override
	// public void onErrorResponse(Exception exception,
	// String code, String msg) {
	// // TODO Auto-generated method stub
	// if (exception instanceof CodeErrorException) {
	// DebugLog.v("bindmsg", msg);
	// Toast.makeText(MainApplication.context, msg, 0).show();
	// } else {
	// Toast.makeText(MainApplication.context, exception.toString(), 0).show();
	//
	// }
	// }
	// }).build();
	// HttpRequest.getDefaultRequestQueue().add(request);
	// }

	private void wechatLogin(String code) {

		MainPresenter mainPresenter = new MainPresenter(this);
		mainPresenter.login("", code, 2);

		// MyJsonRequest<PersonDataBean> request = new
		// MyJsonRequest.Builder<PersonDataBean>().apiVer("100")
		// .typeKey("BY_Weixin_login").param("code", code).requestListener(new
		// XRequestListener<PersonDataBean>() {
		//
		// @Override
		// public void onResponse(PersonDataBean response) {
		// // TODO Auto-generated method stub
		//
		//
		// // Toast.makeText(MainApplication.context, "username"+
		// response.getUsername(), 0).show();
		// // Toast.makeText(MainApplication.context, "password"+
		// response.getPassword(), 10).show();
		// // Toast.makeText(MainApplication.context, "uid"+ response.getUid(),
		// 20).show();
		//
		//
		//
		// SPUtils.put(MainApplication.context, null, SPContants.USERNAME,
		// response.getUsername());
		// SPUtils.put(MainApplication.context, null, SPContants.IS_LOGINED,
		// true);
		// SPUtils.put(MainApplication.context, null, SPContants.EMAIL,
		// response.getEmail());
		// SPUtils.put(MainApplication.context, null, SPContants.NICK,
		// response.getNickname());
		//
		// SPUtils.put(MainApplication.context, null, SPContants.PASSWORD,
		// response.getPassword());
		// SPUtils.put(MainApplication.context, null, SPContants.MOBILE,
		// response.getMobile());
		// SPUtils.put(MainApplication.context, null, SPContants.WX_Openid,
		// response.getWxopenid());
		// SPUtils.put(MainApplication.context, null, SPContants.USER_ID,
		// response.getUid());
		// SPUtils.put(MainApplication.context, null, SPContants.AVATAR_URL,
		// response.getHead());
		// // Intent intent3 = new Intent("changeavart");
		// // sendBroadcast(intent3);
		//
		// // 手机认证
		// if (response.getPhone_validate().equals("1")) {
		//
		// SPUtils.put(MainApplication.context, null, SPContants.USERNAME,
		// response.getUsername());
		// SPUtils.put(MainApplication.context, null, SPContants.IS_LOGINED,
		// true);
		// SPUtils.put(MainApplication.context, null, SPContants.EMAIL,
		// response.getEmail());
		// SPUtils.put(MainApplication.context, null, SPContants.NICK,
		// response.getNickname());
		//
		// SPUtils.put(MainApplication.context, null, SPContants.PASSWORD,
		// response.getPassword());
		// SPUtils.put(MainApplication.context, null, SPContants.MOBILE,
		// response.getMobile());
		// SPUtils.put(MainApplication.context, null, SPContants.WX_Openid,
		// response.getWxopenid());
		// // �����û�Id
		// // Toast.makeText(MainApplication.context, response.getUid(),
		// // 0).show();
		// SPUtils.put(MainApplication.context, null, SPContants.USER_ID,
		// response.getUid());
		// // �����û�ͷ��
		// SPUtils.put(MainApplication.context, null, SPContants.AVATAR_URL,
		// response.getHead());
		//
		// LoginController.setLoginState(new LoginedState());
		// WXEntryActivity.this.finish();
		// Intent intent2 = new Intent(LoginActivity.LOGINEXIT);
		// sendBroadcast(intent2);
		//
		// Intent intent1 = new Intent("changeavart");
		// sendBroadcast(intent1);
		//
		// } else if (response.getPhone_validate().equals("0")) {
		//
		//
		//
		// //Toast.makeText(MainApplication.context, "哈哈哈哈", 0).show();
		// // Intent intent = new Intent();
		// // intent.putExtra("uid", response.getUid());
		// // intent.setClass(WXEntryActivity.this, BindWeChatActivity.class);
		// // response.toString();
		// // startActivity(intent);
		// //
		// // WXEntryActivity.this.finish();
		//
		// }
		//
		// }
		// }).errorListener(new XErrorListener() {
		//
		// @Override
		// public void onErrorResponse(Exception exception,
		// String code, String msg) {
		// if (exception instanceof CodeErrorException) {
		// Toast.makeText(MainApplication.context, msg, 0).show();
		// } else {
		// Toast.makeText(MainApplication.context, exception.toString(),
		// 0).show();
		// }
		// }
		// }).build();
		// Volley.newRequestQueue(MainApplication.context).add(request);
	}

	@Override
	public void update(Observable observable, Object data) {
		ResultEntity result = (ResultEntity) data;
		if (result == null) {
			result = new ResultEntity("-1", "数据格式错误!~", data);
			Log.e("hu", "null");
			ByAlert.alert("登录失败?");
		}

		if (result.hasError()) {
			ByAlert.alert(result.getMsg());
			result.setEventType("unknow");
			Log.e("hu", "随便");
			ByAlert.alert("登录失败");
		} else {
			PersonDataBean response = (PersonDataBean) result.getData();
			// SPUtils.put(MainApplication.context, null, SPContants.USERNAME,
			// response.getUsername());
			// SPUtils.put(MainApplication.context, null, SPContants.IS_LOGINED,
			// true);
			// SPUtils.put(MainApplication.context, null, SPContants.EMAIL,
			// response.getEmail());
			// SPUtils.put(MainApplication.context, null, SPContants.NICK,
			// response.getNickname());
			//
			// SPUtils.put(MainApplication.context, null, SPContants.PASSWORD,
			// response.getPassword());
			// SPUtils.put(MainApplication.context, null, SPContants.MOBILE,
			// response.getMobile());
			// SPUtils.put(MainApplication.context, null, SPContants.WX_Openid,
			// response.getWxopenid());
			// SPUtils.put(MainApplication.context, null, SPContants.USER_ID,
			// response.getUid());
			// SPUtils.put(MainApplication.context, null, SPContants.AVATAR_URL,
			// response.getHead());
			SPUtils.put(this, null, SpPublicParams.UID, response.getUid());
			SPUtils.put(this, null, SpPublicParams.PHONE_MODEL,
					response.getMobile());
			SPUtils.put(this, null, SpPublicParams.USERHEAD, response.getHead());
			SPUtils.put(this, null, SpPublicParams.NICK_NAME,
					response.getNickname());
			SPUtils.put(this, null, SpPublicParams.SEX, response.getSex());
			SPUtils.put(this, null, SpPublicParams.USER_NAME,
					response.getUsername());
			SPUtils.put(this, null, SpPublicParams.COIN, response.getCoin());
			SPUtils.put(this, null, SpPublicParams.FROZINCOIN,
					response.getFronzencoin() == null ? 0 : response.getFronzencoin());
			SPUtils.put(this, null, SpPublicParams.PASSWORD,
					response.getPassword());
			LoginController.setLoginState(new LoginedState());// 切换登录状态
			Intent intent4 = new Intent(LoginActivity.LOGINEXIT);
			sendBroadcast(intent4);
			Intent intent3 = new Intent("changeavart");
			sendBroadcast(intent3);
			Intent intent5 = new Intent("changeshopcart");
			sendBroadcast(intent5);
			if (response.getMobile() == null || "".equals(response.getMobile())) {
				Intent intent6 = new Intent(this, BindTelephoneActivity.class);
				startActivity(intent6);
			} else {
				ByAlert.alert("登录成功");
			}

			Log.e("hu", "success");

		}
	}

}